package com.dragon.www.haier.popupwindow;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.GradientDrawable;
import android.support.percent.PercentRelativeLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.dragon.www.haier.R;
import com.dragon.www.haier.activity.MainActivity;
import com.dragon.www.haier.entity.Device;
import com.dragon.www.haier.entity.DeviceListInfo;
import com.dragon.www.haier.entity.ProfileListInfo;
import com.dragon.www.haier.entity.Room;
import com.dragon.www.haier.entity.ScenceInfo;
import com.dragon.www.haier.entity.ServiceResult;
import com.dragon.www.haier.net.NetHelper;
import com.dragon.www.haier.net.NetUtils;
import com.dragon.www.haier.view.dialog.DevicePickDialog;
import com.dragon.www.haier.view.dialog.RoomPickDialog;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by daiye on 2016/6/3.
 */
public class ConferenceSetPopWindow  extends BasePopupWindow implements RadioGroup.OnCheckedChangeListener {
    private final static int ConferencePopBackgroundColor = 0xD9FF7200;
    private ImageView imageBackConference;
    private RadioGroup radioGroup_devicetype;
    private PercentRelativeLayout devices_settingcontent;
    private LinearLayout mSettingLl;
    private LinearLayout mDeleteLl;
    private TextView mTemperatureTv;
    private TextView mTemperatureReduce;
    private TextView mTemperatureAdd;
    private RadioGroup mAirWindModeRg;
    private RadioGroup mAirWindSpeedRg;
    private Button mSaveBt;
    private Button mDeleteBt;
    private Button mOpenAllBt;
    private Button mCloseAllBt;

    private String mDeviceSelectedType = MainActivity.TYPE_LAMP;  //选中的设备类型

    private int mDeviceSelectedItem = -1;                       //选中的设备索引
    private int mRoomSelectedItem = -1;                         //选中的房间索引

    private List<Room> mRooms = null;                           //总的房间列表
    private List<Room> mSelectedRooms  = new ArrayList<>();     //情景模式下选中的房间
    private RoomSelectedAdapter mRoomSelectedAdapter;           //选中的房间显示适配器
    private ListView mRoomsListView = null;

    private HashMap<String, List<Device>> mAllDevicesMap = new HashMap<String, List<Device>>();         //在房间下总的设备列表,对应房间设备key—object
    private HashMap<String, List<Device>> mSelectedDevicesMap = new HashMap<String, List<Device>>();    //情景模式下选中的设备,对应房间设备key—object
    private DeviceSelectedAdapter mDeviceSelectedAdapter;                                               //选中的设备显示适配器
    private ListView mDeviceListView = null;

    private RoomPickDialog mRoomPickDialog = null;
    private DevicePickDialog mDevicePickDialog = null;

    public ConferenceSetPopWindow(Context context) {
        super(context);
    }

    public void showPopWindow(View view, int xOffsetToView, int yOffsetToView) {
        contentView = LayoutInflater.from(context).inflate(R.layout.conference_setting, null);
        super.showPopWindow(view, xOffsetToView, yOffsetToView);
        imageBackConference = (ImageView) contentView.findViewById(R.id.image_back_setting);
        imageBackConference.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        mOpenAllBt = (Button)contentView.findViewById(R.id.openall_bt);
        mOpenAllBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAllDevice();
            }
        });
        mCloseAllBt = (Button)contentView.findViewById(R.id.closeall_bt);
        mCloseAllBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeAllDevice();
            }
        });

        devices_settingcontent = (PercentRelativeLayout) contentView.findViewById(R.id.devices_settingcontent);
        mSettingLl = (LinearLayout)contentView.findViewById(R.id.setting_ll);
        mTemperatureTv = (TextView)contentView.findViewById(R.id.tv_aircondition_tem);
        mTemperatureReduce = (TextView)contentView.findViewById(R.id.tv_tem_reduce);
        mTemperatureReduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int temp = Integer.parseInt(mTemperatureTv.getText().toString())-1;
                if(temp >= 0)
                    mTemperatureTv.setText(String.valueOf(temp));
            }
        });
        mTemperatureAdd = (TextView)contentView.findViewById(R.id.tv_tem_add);
        mTemperatureAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int temp = Integer.parseInt(mTemperatureTv.getText().toString())+1;
                if(temp <= 30)
                    mTemperatureTv.setText(String.valueOf(temp));
            }
        });
        mSaveBt = (Button)contentView.findViewById(R.id.save_bt);
        mSaveBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int mode = -1;
                int speed = -1;
                int temp = Integer.parseInt(mTemperatureTv.getText().toString());
                int checkModeId = mAirWindModeRg.getCheckedRadioButtonId();
                switch(checkModeId){
                    case R.id.rb_mode_airy:
                        mode = 1;
                        break;
                    case R.id.rb_mode_heat:
                        mode = 2;
                        break;
                    case R.id.rb_mode_cold:
                        mode = 3;
                        break;
                    case R.id.rb_mode_dehumidify:
                        mode = 4;
                        break;
                    case R.id.rb_mode_auto:
                        mode = 5;
                        break;
                }

                int checkSpeedId = mAirWindSpeedRg.getCheckedRadioButtonId();
                switch(checkSpeedId){
                    case R.id.rb_speed_low:
                        speed = 1;
                        break;
                    case R.id.rb_speed_mid:
                        speed = 2;
                        break;
                    case R.id.rb_speed_high:
                        speed = 3;
                        break;
                    case R.id.rb_speed_auto:
                        speed = 4;
                        break;
                }

                saveDeviceParameterForSelectedDevice(temp,mode,speed);
            }
        });

        mDeleteLl = (LinearLayout)contentView.findViewById(R.id.delete_Ll);
        mDeleteBt = (Button)contentView.findViewById(R.id.delete_bt);
        mDeleteBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteDeviceFromSelectedRoom();
                refreshSelectedDevicesInSelectedRoom();
            }
        });

        mAirWindModeRg = (RadioGroup) contentView.findViewById(R.id.radioGroup_wind_mode);
        mAirWindSpeedRg = (RadioGroup) contentView.findViewById(R.id.radioGroup_wind_speed);

        radioGroup_devicetype = (RadioGroup)contentView.findViewById(R.id.radioGroup_devicetype);
        radioGroup_devicetype.setOnCheckedChangeListener(this);

        //防黑边
        this.setBackgroundDrawable(new BitmapDrawable());
        //显示
        GradientDrawable myGrad = (GradientDrawable) contentView.getBackground();
        myGrad.setColor(ConferencePopBackgroundColor);

        //防止虚拟软键盘被弹出菜单遮住
        this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        mRoomsListView = (ListView)contentView.findViewById(R.id.rooms_list);
        mRoomSelectedAdapter = new RoomSelectedAdapter(context);
        mRoomsListView.setAdapter(mRoomSelectedAdapter);
        mRoomsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //增加新房间
                if(mRooms != null){
                    if (position == mSelectedRooms.size()) {
                        mRoomPickDialog = new RoomPickDialog(context);
                        mRoomPickDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                        mRoomPickDialog.setRooms(mRooms);
                        mRoomPickDialog.show();
                        mRoomPickDialog.setLisntener(new RoomPickDialog.OnSelectListener() {
                            @Override
                            public void addRoom(Room room) {
                                if (!isRoomAdded(room.getRoomid())) {
                                    addRoomToProfiles(room);
                                    refreshSelectedRoom();
                                } else {
                                    Toast.makeText(context, "已经添加过该房间了，不能重复添加！", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    } else {
                        //选择某个房间在此基础上修改该房间下设备的参数
                        mRoomSelectedItem = position;
                        mDeviceSelectedItem = -1;
                        refreshSelectedRoom();
                        refreshSelectedDevicesInSelectedRoom();
                    }
                }
            }
        });

        mDeviceListView = (ListView)contentView.findViewById(R.id.devices_list);
        mDeviceSelectedAdapter = new DeviceSelectedAdapter(context);
        mDeviceListView.setAdapter(mDeviceSelectedAdapter);
        mDeviceListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //增加新设备
                List<Device> selectDevices = getSelectedDevicesInSelectedRoom();
                if (position == selectDevices.size()) {
                    if (mRoomSelectedItem == -1 || mSelectedRooms.size() == 0) {
                        Toast.makeText(context, "您还没有选择会议房间", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    List<Device> allDevices = getAllDevicesInSelectedRoom();
                    if (allDevices != null && allDevices.size() == 0) {
                        Toast.makeText(context, mSelectedRooms.get(mRoomSelectedItem).getRoomName() + "的房间下没有" + getDeviceTypeName(), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    mDevicePickDialog = new DevicePickDialog(context);
                    mDevicePickDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    mDevicePickDialog.setDevices(allDevices);
                    mDevicePickDialog.show();
                    mDevicePickDialog.setLisntener(new DevicePickDialog.OnSelectListener() {
                        @Override
                        public void addDevice(Device device) {
                            if (!isDeviceAdded(device.getId())) {
                                addDeviceToSelectedRoom(device);
                                refreshSelectedDevicesInSelectedRoom();
                                setDeviceParameterForSelectedDevice();
                            } else {
                                Toast.makeText(context, "已经添加过该设备了，不能重复添加！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } else {
                    //选择某个设备在此基础上修改该设备的参数
                    mDeviceSelectedItem = position;
                    refreshSelectedDevicesInSelectedRoom();
                    setDeviceParameterForSelectedDevice();
                }
            }
        });

        //从网络同步情景模式下的设备列表到本地
        pulldown();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.setting_lamp:
                mDeviceSelectedType = MainActivity.TYPE_LAMP;
                mDeviceSelectedItem = -1;
                refreshSelectedDevicesInSelectedRoom();
                break;
            case R.id.setting_air:
                mDeviceSelectedType = MainActivity.TYPE_AIR;
                mDeviceSelectedItem = -1;
                refreshSelectedDevicesInSelectedRoom();
                setDeviceParameterForSelectedDevice();
                break;
            case R.id.setting_curtain:
                mDeviceSelectedType = MainActivity.TYPE_CURTAIN;
                mDeviceSelectedItem = -1;
                refreshSelectedDevicesInSelectedRoom();
                break;
            case R.id.setting_entanceguard:
                mDeviceSelectedType = MainActivity.TYPE_ENTANCEGUARD;
                mDeviceSelectedItem = -1;
                refreshSelectedDevicesInSelectedRoom();
                break;
            case R.id.setting_humidifier:
                mDeviceSelectedType = MainActivity.TYPE_HUMIDIFIER;
                mDeviceSelectedItem = -1;
                refreshSelectedDevicesInSelectedRoom();
                break;
            case R.id.setting_plantwall:
                mDeviceSelectedType = MainActivity.TYPE_PLANTWALL;
                mDeviceSelectedItem = -1;
                refreshSelectedDevicesInSelectedRoom();
                break;
        }
    }

    /**
     * 从网络获取房间后设置对应的app设备,会议场景所定义的房间从这个集合中选择
     * 2016/06/01
     */
    public void setRooms(List<Room> rooms){
        this.mRooms = rooms;
    }

    /**
     * 是否在情景模式中已经添加过该房间
     * 2016/06/01
     */
    private boolean isRoomAdded(int roomId){
        boolean is = false;
        for(int i = 0; i < mSelectedRooms.size(); i++)
        {
            if( mSelectedRooms.get(i).getRoomid() == roomId )
            {
                is = true;
                break;
            }
        }
        return is;
    }

    /**
     * 是否在情景模式中已经添加过该设备
     * 2016/06/01
     */
    private boolean isDeviceAdded(int deviceId){
        boolean is = false;
        if( mRoomSelectedItem != -1 ) {
            int roomId = mSelectedRooms.get(mRoomSelectedItem).getRoomid();
            if(mSelectedDevicesMap.containsKey(String.valueOf(roomId))){
                List<Device> devicesList = mSelectedDevicesMap.get(String.valueOf(roomId));
                for(int i=0;i<devicesList.size();i++){
                    if(devicesList.get(i).getId() == deviceId)
                    {
                        is = true;
                        break;
                    }
                }
            }
        }
        return is;
    }

    /**
     * 将某个房间添加到情景列表中
     * 2016/06/01
     */
    private void addRoomToProfiles(Room room){
        mSelectedRooms.add(room);
        List<Device> devices = new ArrayList<>();
        int roomId = room.getRoomid();
        if(!mSelectedDevicesMap.containsKey(String.valueOf(roomId))){
            mSelectedDevicesMap.put(String.valueOf(roomId), devices);
        }
        getRoomDeviceFromNetwork(room.getRoomid());
    }

    /**
     * 将选中的某个设备添加到情景列表中
     * 2016/06/01
     */
    private void addDeviceToSelectedRoom(Device device){
        if( mRoomSelectedItem != -1 ){
            int roomId = mSelectedRooms.get(mRoomSelectedItem).getRoomid();
            if(mSelectedDevicesMap.containsKey(String.valueOf(roomId))) {
                List<Device> devicesList = mSelectedDevicesMap.get(String.valueOf(roomId));
                devicesList.add(device);
                synchronous();
            }
        }
    }

    /**
     * 将选中的某个设备从情景列表中删除
     * 2016/06/01
     */
    private void deleteDeviceFromSelectedRoom(){
        if( mRoomSelectedItem != -1 ) {
            int roomId = mSelectedRooms.get(mRoomSelectedItem).getRoomid();
            if(mSelectedDevicesMap.containsKey(String.valueOf(roomId))) {
                List<Device> devicesList = mSelectedDevicesMap.get(String.valueOf(roomId));
                Device deleteDevice = (Device)mDeviceSelectedAdapter.getItem(mDeviceSelectedItem);
                devicesList.remove(deleteDevice);
                synchronous();
            }
        }
        mDeviceSelectedItem = -1;
    }

    private String getDeviceTypeName(){
        String s = "";
        if(mDeviceSelectedType.equals(MainActivity.TYPE_LAMP)){
            s = "灯光设备";
        }else if(mDeviceSelectedType.equals(MainActivity.TYPE_AIR)){
            s = "空调设备";
        }else if(mDeviceSelectedType.equals(MainActivity.TYPE_CURTAIN)){
            s = "窗帘设备";
        }else if(mDeviceSelectedType.equals(MainActivity.TYPE_ENTANCEGUARD)){
            s = "门禁设备";
        }else if(mDeviceSelectedType.equals(MainActivity.TYPE_HUMIDIFIER)){
            s = "灯加湿器备";
        }else if(mDeviceSelectedType.equals(MainActivity.TYPE_PLANTWALL)){
            s = "植物墙设备";
        }
        return s;
    }

    private void setDeviceParameterForSelectedDevice(){
        if( mDeviceSelectedType.equals(MainActivity.TYPE_AIR) && mDeviceSelectedItem != -1 ){
            List<Device> devices = getSelectedDevicesInSelectedRoom();
            Device deviceSelected = devices.get(mDeviceSelectedItem);
            int temp = deviceSelected.airDeviceTemp;
            int mode = deviceSelected.airDeviceMode;
            int speed = deviceSelected.airDeviceSpeed;
            mTemperatureTv.setText(String.valueOf(temp));
            switch(mode){
                case 1:
                    mAirWindModeRg.check(R.id.rb_mode_airy);
                    break;
                case 2:
                    mAirWindModeRg.check(R.id.rb_mode_heat);
                    break;
                case 3:
                    mAirWindModeRg.check(R.id.rb_mode_cold);
                    break;
                case 4:
                    mAirWindModeRg.check(R.id.rb_mode_dehumidify);
                    break;
                case 5:
                    mAirWindModeRg.check(R.id.rb_mode_auto);
                    break;
            }
            switch(speed){
                case 1:
                    mAirWindSpeedRg.check(R.id.rb_speed_low);
                    break;
                case 2:
                    mAirWindSpeedRg.check(R.id.rb_speed_mid);
                    break;
                case 3:
                    mAirWindSpeedRg.check(R.id.rb_speed_high);
                    break;
                case 4:
                    mAirWindSpeedRg.check(R.id.rb_speed_auto);
                    break;
            }
        }
    }

    private void saveDeviceParameterForSelectedDevice(int temp, int mode, int speed){
        if( mDeviceSelectedType.equals(MainActivity.TYPE_AIR)){
            List<Device> devices = getSelectedDevicesInSelectedRoom();
            Device deviceSelected = devices.get(mDeviceSelectedItem);
            deviceSelected.airDeviceMode = mode;
            deviceSelected.airDeviceSpeed = speed;
            deviceSelected.airDeviceTemp = temp;
            synchronous();
        }
    }

    /**
     * 获得选中房间下某个设备类型下的选中设备，比如说房间1的选中的（添加到情景列表中的）灯光设备
     * 2016/06/01
     */
    private List<Device> getSelectedDevicesInSelectedRoom(){
        List<Device> devicesTypeList = new ArrayList<>();
        if( mRoomSelectedItem != -1 ){
            int roomId = mSelectedRooms.get(mRoomSelectedItem).getRoomid();
            if(mSelectedDevicesMap.containsKey(String.valueOf(roomId))){
                List<Device> devicesList = mSelectedDevicesMap.get(String.valueOf(roomId));
                for(int i=0;i<devicesList.size();i++){
                    if(devicesList.get(i).getType().equals(mDeviceSelectedType))
                        devicesTypeList.add(devicesList.get(i));
                }
            }
        }
        return devicesTypeList;
    }


    /**
     * 获得选中房间下某个设备类型下的所有设备，比如说房间1的所有灯光设备
     * 2016/06/01
     */
    private List<Device> getAllDevicesInSelectedRoom(){
        List<Device> devicesTypeList = new ArrayList<>();
        if( mRoomSelectedItem != -1 ){
            int roomId = mSelectedRooms.get(mRoomSelectedItem).getRoomid();
            if(mAllDevicesMap.containsKey(String.valueOf(roomId))){
                List<Device> devicesList = mAllDevicesMap.get(String.valueOf(roomId));
                for(int i=0;i<devicesList.size();i++){
                    if(devicesList.get(i).getType().equals(mDeviceSelectedType))
                        devicesTypeList.add(devicesList.get(i));
                }
            }
        }
        return devicesTypeList;
    }

    /**
     * 刷新选择的房间列表
     * 2016/06/01
     */
    private void refreshSelectedRoom(){
        mRoomSelectedAdapter.notifyDataSetChanged();
    }

    /**
     * 当选择了某个房间或者点击了不同的设备类型后刷新具体的设备列表
     * 2016/06/01
     */
    private void refreshSelectedDevicesInSelectedRoom(){
        mDeviceSelectedAdapter.notifyDataSetChanged();
        if( mDeviceSelectedItem != -1 ){
            devices_settingcontent.setVisibility(View.VISIBLE);
            if( mDeviceSelectedType.equals(MainActivity.TYPE_AIR) ){
                mSettingLl.setVisibility(View.VISIBLE);
            }else{
                mSettingLl.setVisibility(View.GONE);
            }
        }else{
            devices_settingcontent.setVisibility(View.GONE);
        }
    }

    /**
     * 从网络获取房间对应的设备
     * 2016/06/01
     */
    public void getRoomDeviceFromNetwork(final int roomId) {
        NetHelper.getDevices(context, roomId, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getCode().equals("0000")) {
                    //保存设备信息
                    final DeviceListInfo deviceListInfo = (DeviceListInfo) rspData;
                    List<Device> devices = deviceListInfo.getDevices();
                    if (!mAllDevicesMap.containsKey(String.valueOf(roomId))) {
                        mAllDevicesMap.put(String.valueOf(roomId), devices);
                    }
                }
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        }, DeviceListInfo.class);
    }

    /**
     * 把情景模式中的所有设备打开
     * 2016/06/01
     */
    private void openAllDevice(){
        Iterator iter = mSelectedDevicesMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            List<Device> val = (List<Device>) entry.getValue();


        }
    }

    /**
     * 把情景模式中的所有设备关闭
     * 2016/06/01
     */
    private void closeAllDevice(){
        Iterator iter = mSelectedDevicesMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            List<Device> val = (List<Device>) entry.getValue();


        }
    }

    /**
     * 同步设置的情景模式设备到服务器(遍历mSelectedDevicesMap然后上传)
     * 2016/06/01
     */
    private void  synchronous(){
        if( mSelectedDevicesMap != null ){
            //构建房间集合体
            List<Map<String, Object>> roomlists = new ArrayList<>();
            Iterator iter = mSelectedDevicesMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = (String)entry.getKey();
                List<Device> val = (List<Device>)entry.getValue();
                if( val.size() != 0 ){
                    //构建每个房间的map结构体
                    Map<String, Object> mapRooms = new HashMap<>();
                    List<Map<String, Object>> devicelists = new ArrayList<>();
                    for(int i = 0; i < val.size(); i++ ){
                        //构建每个设备的map结构体
                        Device device = val.get(i);
                        Map<String, Object> mapDevice = new HashMap<>();
                        mapDevice.put("id", device.getId());
                        mapDevice.put("name",device.getDeviceName());
                        mapDevice.put("remark",device.getDescription());
                        mapDevice.put("equipType",device.getType());
                        if(device.getType().equals(MainActivity.TYPE_AIR)) {
                            mapDevice.put("airDeviceTemp", device.airDeviceTemp);
                            mapDevice.put("airDeviceMode", device.airDeviceMode);
                            mapDevice.put("airDeviceSpeed", device.airDeviceSpeed);
                        }
                        devicelists.add(mapDevice);
                    }

                    mapRooms.put("infoList",devicelists);
                    mapRooms.put("roomId",key);
                    roomlists.add(mapRooms);
                }
            }

            NetHelper.updateScene(context, roomlists, new NetUtils.NetCallBack<ServiceResult>() {
                @Override
                public void success(ServiceResult rspData) {
                    if (rspData.getCode().equals("0000")) {
                        Toast.makeText(context, "场景已和服务器同步完成！", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(context, "场景同步失败，原因"+rspData.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void failed(String msg) {
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                }
            }, ServiceResult.class);
        }
    }

    /**
     * 从服务器下载同步情景模式设备到本地(同步设备列表到mSelectedDevicesMap)
     * 2016/06/01
     */
    private void  pulldown(){
        NetHelper.getScene(context, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getCode().equals("0000")) {
                    ScenceInfo scenceInfo = (ScenceInfo) rspData;
                    String str = scenceInfo.getContent();

                    try{
                        Gson gson = new Gson();
                        ProfileListInfo roomProfileListInfo = gson.fromJson(str, ProfileListInfo.class);
                        List<ProfileListInfo.ProfileList> roomProfileList = roomProfileListInfo.getData();
                        for(int i = 0; i < roomProfileList.size(); i++){
                            ProfileListInfo.ProfileList roomProfile = roomProfileList.get(i);
                            String roomId = roomProfile.getRoomId();
                            List<Device> devices = roomProfile.getDevices();
                            mSelectedDevicesMap.put(roomId, devices);

                            //从网络获取的配置设置到本地
                            if( mRooms != null){
                                for(int a = 0; a < mRooms.size(); a++){
                                    Room room = mRooms.get(a);
                                    if(room.getRoomid() == Integer.parseInt(roomId)){
                                        addRoomToProfiles(room);
                                    }
                                }
                            }

                            //始终默认选择第一个room
                            mRoomSelectedItem = 0;
                        }

                        refreshSelectedRoom();
                        refreshSelectedDevicesInSelectedRoom();
                        Toast.makeText(context, "场景同步到本地完成！", Toast.LENGTH_SHORT).show();
                    }catch(Exception e){
                        Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
                        Log.e("错误", e.toString());
                    }
                } else if (rspData.getCode().equals("0001")) {
                    Toast.makeText(context, "服务器上暂时还没有保存有会议配置！", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(context, "场景同步失败，原因" + rspData.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        }, ScenceInfo.class);
    }

    /**
     * 房间列表适配器
     * 2016/06/01
     */
    public class RoomSelectedAdapter extends BaseAdapter {
        public class RoomViewHolder {
            public TextView tv_room;
            public View v_select;
        }

        private Context mcontext;

        public RoomSelectedAdapter(Context context) {
            mcontext = context;
        }

        @Override
        public int getCount() {
            return mSelectedRooms.size()+1;
        }

        @Override
        public Object getItem(int position) {
            if(position < mSelectedRooms.size())
                return mSelectedRooms.get(position);
            else
                return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            RoomViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new RoomViewHolder();
                convertView = LayoutInflater.from(mcontext).inflate(R.layout.room_selected_item, parent, false);
                viewHolder.tv_room = (TextView) convertView.findViewById(R.id.tv_room);
                viewHolder.v_select = convertView.findViewById(R.id.select_v);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (RoomViewHolder) convertView.getTag();
            }
            if(position < mSelectedRooms.size()){
                final Room room = mSelectedRooms.get(position);
                if( mRoomSelectedItem !=-1 && mRoomSelectedItem == position){
                    viewHolder.v_select.setVisibility(View.GONE);
                }else{
                    viewHolder.v_select.setVisibility(View.VISIBLE);
                }
                viewHolder.tv_room.setText(room.getRoomName());
            }else{
                viewHolder.v_select.setVisibility(View.VISIBLE);
                viewHolder.tv_room.setText("+");
            }

            return convertView;
        }
    }

    /**
     * 设备列表适配器
     * 2016/06/01
     */
    public class DeviceSelectedAdapter extends BaseAdapter {
        public class DeviceViewHolder {
            public View v_select;
            public TextView tv_device;
        }

        private Context mcontext;

        public DeviceSelectedAdapter(Context context) {
            mcontext = context;
        }

        @Override
        public int getCount() {
            List<Device> selectDevices = getSelectedDevicesInSelectedRoom();
            return selectDevices.size()+1;
        }

        @Override
        public Object getItem(int position) {
            List<Device> selectDevices = getSelectedDevicesInSelectedRoom();
            if(position < selectDevices.size())
                return selectDevices.get(position);
            else
                return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            DeviceViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new DeviceViewHolder();
                convertView = LayoutInflater.from(mcontext).inflate(R.layout.device_selected_item, parent, false);
                viewHolder.tv_device = (TextView) convertView.findViewById(R.id.tv_device);
                viewHolder.v_select = convertView.findViewById(R.id.select_v);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (DeviceViewHolder) convertView.getTag();
            }
            List<Device> selectDevices = getSelectedDevicesInSelectedRoom();
            if(position < selectDevices.size()){
                final Device device = selectDevices.get(position);
                if( mDeviceSelectedItem !=-1 && mDeviceSelectedItem == position){
                    viewHolder.v_select.setVisibility(View.VISIBLE);
                }else{
                    viewHolder.v_select.setVisibility(View.GONE);
                }
                viewHolder.tv_device.setText(device.getDeviceName());
            }else{
                viewHolder.v_select.setVisibility(View.GONE);
                viewHolder.tv_device.setText("+");
            }

            return convertView;
        }
    }
}
